package com.ls.modules.sys.biz.manager;

import com.google.code.kaptcha.Producer;
import com.ls.base.exception.RRException;
import com.ls.base.utils.DateUtils;
import com.ls.common.baseClass.BackStageService;
import com.ls.modules.sys.dal.jpa.dao.SysCaptchaDao;
import com.ls.modules.sys.dal.jpa.entity.SysCaptchaEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Optional;

/**
 * @author: xiaosu
 * @date: 2018-09-25  18:16
 */
@Service("sysCaptchaManager")
public class SysCaptchaManager extends BackStageService {

    @Autowired
    private Producer producer;

    @Autowired
    private SysCaptchaDao sysCaptchaDao;

    /**
     * 获取图片验证码
     */
    public BufferedImage getCaptcha(String uuid){
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        sysCaptchaDao.save(captchaEntity);

        return producer.createImage(code);

    }

    /**
     * 验证码效验
     *
     * @param uuid uuid
     * @param code 验证码
     * @return true：成功  false：失败
     */
    public  boolean validate(String uuid, String code){

        Optional<SysCaptchaEntity> optional=  sysCaptchaDao.findById(uuid);
        if(!optional.isPresent()){
          return  false;
      }
        SysCaptchaEntity captchaEntity =optional.get();
        //删除验证码
        sysCaptchaDao.deleteById(uuid);

        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }



}
